package com.wandian.cqcsk.mvvm.mine.helpandsuggest.helpsuggest;

import android.app.Activity;
import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.JsonObject;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.bean.OSSDataBean;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.OssManager;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.wandian.cqcsk.data.BaseAppApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;


/**
 * @author Administrator
 * @date 2019/12/18-16:11
 * @description HelpSuggestViewModel
 **/
public class HelpSuggestViewModel extends BaseViewModel {
    private BaseAppApi baseAppApi;
    private long oosTime=0;
    private List<String> sendImgList=new ArrayList<>();
    private String imgPathListStr = "";
    public MutableLiveData<OSSDataBean> oosBean = new MutableLiveData<>();
    public HelpSuggestViewModel(@NonNull Application application) {
        super(application);
        baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
    }
    public void sendSuggest(String text,String imgStr){
        showDialog();
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("content",text);
        hashMap.put("imgStr",imgStr);
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.sendSuggest(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {

                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("sendSuggest",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                           ToastUtil.show("已提交");
                           finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        if(!UIUtils.isEmpty(e.getMessage())){
                            ToastUtil.show(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //获取oosToken
    public void getOOSToken(){
        if(System.currentTimeMillis()-oosTime>10*60*1000 || UIUtils.isEmpty(oosBean.getValue())){
            oosTime = System.currentTimeMillis();
            showDialog();
            JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
            jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
            RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.getOOSToken(jsonObject))
                    .subscribe(new Observer<BaseBean<Object>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }
                        @Override
                        public void onNext(BaseBean<Object> bean) {
                            dismissDialog();
                            Log.d("getOOSToken",   JsonUtil.toJson(bean));
                            if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                                String json = AESUtils.getInstance().decrypt(bean.getData())+"";
                                if(!UIUtils.isEmpty(json) && json.length()>4){
                                    OSSDataBean ossDataBean =JsonUtil.parseJsonToBean(json,OSSDataBean.class);
                                    oosBean.setValue(ossDataBean);
                                }else {
                                    oosBean.setValue(null);
                                }
                            }else {
                                oosBean.setValue(null);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            oosBean.setValue(null);
                            dismissDialog();
                            Log.d("getOOSToken",   JsonUtil.toJson(e));
                            if(!UIUtils.isEmpty(e.getMessage())){
                                ToastUtil.show(e.getMessage());
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }else {
            oosBean.setValue(oosBean.getValue());
        }
    }

    // 上传图片
    public void upLoadImg(Activity activity, OSSDataBean ossDataBean , List<String> imgPath, String upTitle){

        for(int i=0;i<imgPath.size();i++){
            if(UIUtils.isEmpty(imgPath.get(i))){
                sendImgList.add("");
            }else {
                showDialog();
                OssManager.getInstance().upload(activity, ossDataBean,imgPath.get(i),OssManager.getSuggestPicPath(imgPath.get(i)), 0, new OssManager.OnUploadListener() {

                            @Override
                            public void onProgress(int position, long currentSize, long totalSize) {
                            }

                            @Override
                            public void onSuccess(int position, String uploadPath, String imageUrl) {
                                activity.runOnUiThread(() -> {
                                    dismissDialog();
                                    Log.d("Oss-uploadPath",uploadPath+"");
                                    Log.d("Oss-imageUrl", imageUrl +"");
                                    sendImgList.add(imageUrl);
                                    imgPathListStr = imgPathListStr+imageUrl+",";
                                    sendPic(upTitle,imgPath);
                                });

                            }

                            @Override
                            public void onFailure(int position) {
                                activity.runOnUiThread(() -> {
                                    sendImgList.add("");
                                    sendPic(upTitle,imgPath);
                                    dismissDialog();
                                });
                            }
                        }
                );
            }
        }

    }

    private void sendPic(String upTitle,List<String> imgPath){
        if(sendImgList.size() == imgPath.size()){
            sendSuggest(upTitle,imgPathListStr);
            for(int i=0;i<imgPath.size();i++){
                if(!UIUtils.isEmpty(imgPath.get(i))) FileUtil.deleteFileByPath(imgPath.get(i));
            }
        }
    }
}
